//
//  AlertManagedObject.m
//  ALittleReminder
//
//  Created by George on 11-11-04.
//
//

#import "AlertManagedObject.h"
#import <AssetsLibrary/ALAssetRepresentation.h>

NSDateFormatter *dateFormatter = nil;

@implementation AlertManagedObject

@dynamic name, date, imageURLString, text, audioFileName;

- (NSString *) timeToString
{
    if (!dateFormatter) {
        dateFormatter = [[NSDateFormatter alloc]init];
        [dateFormatter setLocale:[NSLocale systemLocale]];
        [dateFormatter setDateFormat:@"MMM.d.y 'at' h:mm a"];
    }
    return [dateFormatter stringFromDate:self.date];
}

- (void) useImage:(SetImageBlock) setImageBlock {
    NSString * imageURLString = [self imageURLString];
    //NSLog(@"use image URL:%@",imageURLString);
    if (imageURLString) {
        NSURL * url = [NSURL URLWithString:imageURLString];
        
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:url
                 resultBlock:^(ALAsset *asset)
        {
            ALAssetRepresentation *representation = [asset defaultRepresentation];
            setImageBlock([UIImage imageWithCGImage:[representation fullResolutionImage]]);
        }
                failureBlock:^(NSError *error)
        {
            NSLog(@"couldn't get asset: %@", error);
            setImageBlock(nil);
        }];
    }else{
        setImageBlock(nil);
    }
}

- (void) useThumbnail:(SetImageBlock) setImageBlock {
    NSString * imageURLString = [self imageURLString];
    //NSLog(@"use image URL:%@",imageURLString);
    if (imageURLString) {
        NSURL * url = [NSURL URLWithString:imageURLString];
        
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:url
                 resultBlock:^(ALAsset *asset)
         {
             setImageBlock([UIImage imageWithCGImage:[asset thumbnail]]);
         }
                failureBlock:^(NSError *error)
         {
             NSLog(@"couldn't get asset: %@", error);
             setImageBlock(nil);
         }];
    }else{
        setImageBlock(nil);
    }
}

- (void) removeAudioFile{
    if (self.audioFileName) {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSURL *audioUrl = [[NSURL alloc] initWithString:self.audioFileName];;
        NSError *error;
        if ([fileManager removeItemAtURL:audioUrl error:&error]){
            self.audioFileName = nil;
        }else{
            NSLog(@"Unable to delete file: %@", [error localizedDescription]);
        }
    }
}

@end
